package com.carlosk.kandicar.ui.adapter.holder;

import java.lang.reflect.Constructor;

import android.view.View;
import android.view.View.OnClickListener;

import com.carlosk.kandicar.domain.BaseObject;
import com.carlosk.kandicar.linstener.CommonLinstener;
import com.carlosk.kandicar.util.ViewUtil;

/**
 * 用户填充Adapter的帮助类
 * 
 * @author carlos carlosk@163.com
 * @version 创建时间：Mar 9, 2014 2:21:29 PM 类说明
 */

public abstract class BaseHolder<T> extends BaseObject {
	@SuppressWarnings({ "unchecked", "rawtypes" })
	/**
	 * 在getView方法里调用
	 * @author carlos carlosk@163.com
	 * @version 创建时间：2014年4月7日 下午1:40:00
	 */
	public static HolderAndView initView(View convertView,
			Class<? extends Object> c, int layoutId, int position, Object domain) {
		BaseHolder holder = null;
		if (null == convertView) {
			convertView = ViewUtil.buildView(layoutId);
			try {
				Constructor<? extends Object> method = c
						.getDeclaredConstructor(View.class);
				Object o = method.newInstance(convertView);
				holder = (BaseHolder) o;
				convertView.setTag(holder);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			holder = (BaseHolder) (convertView.getTag());
		}
		holder.fillData(position, domain, convertView);
		HolderAndView holderAndView = new HolderAndView();
		holderAndView.holder = holder;
		holderAndView.view = convertView;
		return holderAndView;
	}

	/**
	 * 返回简单的view
	 * 
	 * @author carlos carlosk@163.com
	 * @version 创建时间：2014年4月7日 下午1:45:17
	 */
	public static View initViewSimpleReturn(View convertView,
			Class<? extends BaseHolder<? extends Object>> c, int layoutId,
			int position, Object domain) {
		HolderAndView holderAndView = initView(convertView, c, layoutId,
				position, domain);
		return holderAndView.view;
	}

	// 临时封装Holder和View的
	public static class HolderAndView {
		public View view;
		public BaseHolder< ? extends Object> holder;
	}

	public void setDefault(View view) {
		// 隐藏所有的view
		hideAllView();
	}

	public BaseHolder(View convertView) {
		convertView.setTag(this);
	}

	/**
	 * 隐藏所有的view
	 * 
	 * @author carlos carlosk@163.com
	 * @version 创建时间：Mar 9, 2014 2:23:41 PM
	 */
	public abstract void hideAllView();

	private T t;

	public void fillData(int position, T t1, View convertView) {
		setDefault(convertView);
		this.t = t1;
		// 添加事件
		convertView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (t == null || !(t instanceof BaseObject)) {
					return;
				}
				BaseObject object = (BaseObject) t;
				CommonLinstener commonLinstener = object.getCommonLinstener();
				if (null != commonLinstener) {
					commonLinstener.onClickOne(object);
				}
			}
		});
		fillDataByView(position, t, convertView);
	}

	/**
	 * 填充数据,给子类实现
	 * 
	 * @author carlos carlosk@163.com
	 * @version 创建时间：Mar 9, 2014 2:25:11 PM
	 */
	public abstract void fillDataByView(int position, T t, View view);
}
